# coding=utf-8
#

import os
import json

from django.core.management.base import BaseCommand

from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.cvm.v20170312 import cvm_client
from tencentcloud.cvm.v20170312 import models

from iminer.utils import check_pid

from iminer.tidal.models import TidalAgent


#TX_API_AK = "AKID53SmxxlMkxxlMcT9ctRp10nMirnVzJQK"
#TX_API_SK = "iFZfYEhwxlLk2oQvOlz4A7vXyDIE1c1H"

TX_API_AK = "AKIDIarCd1C3HdwAU9zux7IjDqhCsegpGoP5"
TX_API_SK = "waHxZdfzSh8iIHGKd8xtUzfbgOTc7rfa"


class Command(BaseCommand):
    help = "定时删除腾讯云的机器实例"

    def handle(self, *args, **options):
        """ 定时删除腾讯云机器实例 """
        task_name = "pid/daily_get_tx_servers"

        try:
            old_pid = int(open(task_name).read())
        except FileNotFoundError:
            old_pid = 0
        except ValueError:
            old_pid = 0

        cur_pid = os.getpid()
        if not old_pid or not check_pid(old_pid):
            with open(task_name, "w") as fp:
                fp.write(str(cur_pid))

            limit = 100
            cred = credential.Credential(TX_API_AK, TX_API_SK)

            project_lists = [
                    {"endpoint": "cvm.ap-beijing.tencentcloudapi.com", "zone": "ap-beijing", "cn_name": "北京"},
                    {"endpoint": "cvm.ap-nanjing.tencentcloudapi.com", "zone": "ap-nanjing", "cn_name": "南京"},
                    {"endpoint": "cvm.ap-shanghai.tencentcloudapi.com", "zone": "ap-shanghai", "cn_name": "上海"},
            ]

            for project_az_info in project_lists:

                # total的数量
                offset = 0

                # 计数器
                counter = 0
                total_count = 0

                # 服务器列表，批量删除用
                instance_list = []

                # 是否删完的标记
                not_done_yet = True

                # 腾讯云API初始化用的参数
                endpoint = project_az_info["endpoint"]
                zone = project_az_info["zone"]
                cn_name = project_az_info["cn_name"]

                print(endpoint, zone, cn_name)

                # 初始化腾讯云API实例
                httpProfile = HttpProfile()
                httpProfile.endpoint = endpoint

                clientProfile = ClientProfile()
                clientProfile.httpProfile = httpProfile
                client = cvm_client.CvmClient(cred, zone, clientProfile)
                req = models.DescribeInstancesRequest()

                while not_done_yet:

                    params = {"Offset": offset, "Limit": limit}
                    print(params)

                    req.from_json_string(json.dumps(params))
                    resp = client.DescribeInstances(req)

                    if not total_count:
                        total_count = resp.TotalCount

                    for instance_info in resp.InstanceSet:
                        instance_id = instance_info.InstanceId
                        counter += 1
                        instance_list.append(instance_id)

                    # 最后判断count
                    if counter >= total_count or not len(resp.InstanceSet):
                        not_done_yet = False

                    offset += limit

                for instance_id in instance_list:  
                    ta, _ = TidalAgent.objects.get_or_create(idc="tencent", instance_id=instance_id)
                    ta.endpoint = endpoint
                    ta.zone = zone
                    ta.status = 1
                    ta.save()
